import Axios from '@/util/http'
import api from '@/config/api'
import { Message } from 'element-ui'

const state = {
  shoppingList: [],
  shopcartNum: 0
}
const mutations = {
  setShopcart: (state, data) => {
    if (Array.isArray(data) && data.length > 0) {
      state.shoppingList = data
    } else {
      state.shoppingList = []
    }
  },
  setShopcartNum: (state, data) => {
    if (data) {
      state.shopcartNum = data
    } else {
      state.setShopcartNum = 0
    }
  }
}
const actions = {
  getShopcart ({dispatch, commit, state}, params = {}) {
    return new Promise(resolve => {
      Axios.post(api + '/pc/orderShoppingCart/myShoppingCarView', params).then(res => {
        if (res.responseCode === '0000') {
          commit('setShopcart', res.data)
          return resolve(res.data)
        }
      })
    })
  },
  delShopcart ({dispatch, commit, state}, params = {}) {
    return new Promise((resolve, reject) => {
      Axios.post(api + '/pc/orderShoppingCart/delShoppingCar', params).then(res => {
        if (res.responseCode === '0000') {
          Message({
            type: 'success',
            duration: 1500,
            message: res.responseMsg,
            onClose: () => {
              dispatch('getShopcart')
              return resolve()
            }
          })
        } else {
          Message({
            type: 'error',
            duration: 1500,
            message: res.responseMsg,
            onClose: () => {
              return resolve()
            }
          })
        }
      }).catch(err => {
        return reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
